package com.wjk.kylin.rpc.core.invoker.impl;

import com.wjk.kylin.rpc.core.config.RpcConsumerConfigProperties;
import com.wjk.kylin.rpc.core.invoker.RpcConsumerFactory;
import com.wjk.kylin.rpc.core.invoker.annotation.RpcReference;
import com.wjk.kylin.rpc.core.invoker.reference.RpcReferenceBean;
import com.wjk.kylin.rpc.core.provider.RpcProviderFactory;
import com.wjk.kylin.rpc.core.util.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.util.ReflectionUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * kylin-rpc consumer factory, init service-registry and spring-bean by annotation (for spring)
 * @author wjk
 */
public class RpcSpringConsumerFactory implements BeanPostProcessor, InitializingBean, DisposableBean {
    private static final Logger LOGGER = LoggerFactory.getLogger(RpcSpringConsumerFactory.class);

    private RpcConsumerConfigProperties properties;

    public void setProperties(RpcConsumerConfigProperties properties) {
        this.properties = properties;
    }

    private RpcConsumerFactory consumerFactory;


    /**
     * 执行顺序 postProcessBeforeInstantiation -> afterPropertiesSet -> postProcessAfterInstantiation
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        LOGGER.info(">>>>>>>>>>> kylin-rpc consumer factory start");

        // start consumer factory
        consumerFactory = new RpcConsumerFactory(properties.getRegistry().getType(), properties.getRegistry().getAddress());
        consumerFactory.start();
    }

    /**
     * 如果返回的不是null，对原始的bean 进行替换
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // collection
        final Set<String> serviceKeyList = new HashSet<>();

        // parse RpcReferenceBean 采用反射 对bean对象重新设置 RpcReference 的注入属性字段
        ReflectionUtils.doWithFields(bean.getClass(), field -> {
            if (field.isAnnotationPresent(RpcReference.class)) {
                // valid
                Class<?> interfaceName = field.getType();
                if (!interfaceName.isInterface()) {
                    throw new RpcException("Kylin-rpc, reference(RpcReference) must be interface.");
                }

                RpcReference rpcReference = field.getAnnotation(RpcReference.class);

                // init reference bean
                RpcReferenceBean referenceBean = new RpcReferenceBean();
                referenceBean.setInterfaceName(interfaceName);
                referenceBean.setVersion(rpcReference.version());
                referenceBean.setTimeout(rpcReference.timeout());
                referenceBean.setConsumerFactory(consumerFactory);
                referenceBean.setSerializer(properties.getSerializer());
                referenceBean.setAccessToken(properties.getAccessToken());
                referenceBean.setLoadBalance(rpcReference.loadBalance());//使用注解
                referenceBean.setCallType(rpcReference.callType());//调用方式
                // get proxyObj
                Object serviceProxy = null;
                try {
                    serviceProxy = referenceBean.getObject();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                // set bean
                field.setAccessible(true);
                field.set(bean, serviceProxy);

                LOGGER.info(">>>>>>>>>>> kylin-rpc consumer factory init reference bean success. serviceKey = {}, bean.field = {}.{}",
                        RpcProviderFactory.makeServiceKey(interfaceName.getName(), rpcReference.version()), beanName, field.getName());

                // collection
                String serviceKey = RpcProviderFactory.makeServiceKey(interfaceName.getName(), rpcReference.version());
                serviceKeyList.add(serviceKey);

            }
        });

        // 启动项目时 提前 加入缓存
        if (consumerFactory.getRegister() != null) {
            try {
                consumerFactory.getRegister().discovery(serviceKeyList);
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
            }
        }

        return bean;
    }


    @Override
    public void destroy() throws Exception {
        LOGGER.info(">>>>>>>>>>> kylin-rpc consumer factory destroy");

        // stop consumer factory
        consumerFactory.stop();
    }
}
